import axios from "axios";
import type { InternalAxiosRequestConfig, AxiosError, AxiosInstance, AxiosResponse } from "axios";

import { ElMessage } from "element-plus";

const baseUrl: string = import.meta.env.VITE_BASE_URL;

const service: AxiosInstance = axios.create({
    baseURL: baseUrl,
    timeout: 60000,
});

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 在发送请求之前做些什么
        // if (store.getters["user/token"]) {
        //     config.headers["token"] = store.state.user.token;
        // }
        return config;
    },
    (error: AxiosError) => {
        // 对请求错误做些什么
        console.log("err" + error);
        ElMessage({
            message: error.message,
            type: "error",
            duration: 3 * 1000,
        });
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        // 对响应数据做点什么
        const res = response.data;
        if (res.code !== 200) {
            ElMessage({
                message: res.message || "Error",
                type: "error",
                duration: 3 * 1000,
            });
            return Promise.reject(new Error(res.message || "Error"));
        } else {
            return res;
        }
    },
    (error: AxiosError) => {
        // 对响应错误做点什么
        console.log("err" + error);
        ElMessage({
            message: error.message,
            type: "error",
            duration: 3 * 1000,
        });
        return Promise.reject(error);
    }
);

export default service;
